﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Repository;

using WarehouseManagement.Presenters.Import;
using WarehouseManagement.ViewModels.Import;
using WarehouseManagement.Views.Shared;
using DevExpress.XtraGrid.Views.Grid;
using WarehouseManagement.DataAccess;

using WarehouseManagement.Shared;
using WarehouseManagement.BusinessLogic.BC;
using DevExpress.XtraBars;
using WarehouseManagement.BusinessLogic.DTO;
using WarehouseManagement.Views.Supplier;
using WarehouseManagement.Views.Merchandise;

namespace WarehouseManagement.Views.Export
{
    public partial class NewEditImport : XtraForm, IView<NewImportPresenter>, INewImportViewModel
    {
        private NewImportPresenter _presenter;
        public enum EditMode { New, EditExisting }
        private EditMode _editMode;
        public NewImportPresenter.ImportSaved OnImportSaved;
        private CurrencyBC _currencyBC;

        private bool _dataChanged = false;
        private bool _dataSaved = false;

        private NewEditImport()
        {

            InitializeComponent();
            _currencyBC = new CurrencyBC();
            _presenter = SetupPresenter();
        }



        public NewEditImport(EditMode mode)
            : this()
        {
            CurrentEditMode = mode;
            txtImportDate.Properties.MaxValue = DateTime.Now;
            if (CurrentEditMode == EditMode.New)
                _presenter.CreateNewImportNumber();
            _presenter.InitializeView();
        }

        public int MerchandiseId { get; set; }
        public decimal UnitPriceAfterTax { get; set; }
        //public void LoadImportListOnDemand()
        //{
        //    _presenter.LoadImportList(ImportNumber, this.MerchandiseId);
        //}

        public NewImportPresenter SetupPresenter()
        {
            var p = new NewImportPresenter();
            p.RegisterViewModel(this);
            return p;
        }



        private void NewImport_Load(object sender, EventArgs e)
        {

            btnCreateNewImportNumber.Enabled = (_editMode != EditMode.New);
            HandleControls();
            if (_editMode == EditMode.EditExisting)
            {
                _presenter.LoadExistingImportList(ImportNumber);
            }
            lkCurrency_EditValueChanged(lkCurrency, e);
        }

        private void grvImportList_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle == -2147483648 || e.RowHandle == -2147483647)
                return;
            e.Info.DisplayText = (e.RowHandle + 1).ToString();
        }

        public void LoadImportListFromPO()
        {
            POBC poBC = new POBC();
            var poId = poBC.GetPOIdByNumber(this.ImportForDocumentNumber);
            if (poId == Guid.Empty)
                return;
            var list = poBC.GetPOList(poId);
            var list2 = list.Select(e => new ImportDetailDTO()
            {
                CreatedBy = GlobalMemory.CurrentLoginUser,
                CreatedDate = DateTime.Now,
                ExchangeRate = e.PO.ExchangeRate,
                Id = Guid.NewGuid(),
                ImportId = this.ImportId,
                MerchandiseId = e.MerchandiseId,
                OriginPrice = e.UnitPrice,
                Quantity = e.Quantity,
                ShippingFee = e.ShippingFee,
                Tax = e.Tax
            });

            foreach(var item in list2)
            {
                ImportDetailList.Add(item);
            }
        }


        public Guid ImportId
        {
            get
            {
                return Guid.Parse(this.Tag.ToString());
            }
            set
            {
                this.Tag = value;
            }
        }

        public DateTime ImportDate
        {
            get
            {
                return txtImportDate.DateTime;
            }
            set
            {
                txtImportDate.DateTime = value;
            }
        }

        public string ImportReason
        {
            get
            {
                return txtReason.Text;
            }
            set
            {
                txtReason.Text = value;
            }
        }

        public string Notes
        {
            get
            {
                return txtNotes.Text;
            }
            set
            {
                txtNotes.Text = value;
            }
        }

        public BindingList<ImportDetailDTO> ImportDetailList
        {
            get
            {
                return grdImportList.DataSource as BindingList<ImportDetailDTO>;
            }
            set
            {
                grdImportList.DataSource = value;
            }
        }


        public IEnumerable<dynamic> MerchandiseList
        {
            get
            {
                return ipeMerchandiseLookup.DataSource as IEnumerable<dynamic>;
            }
            set
            {
                ipeMerchandiseLookup.DataSource = value;
                ipeMerchandiseLookup.NullText = "(Chọn mặt hàng)";
                ipeMerchandiseLookup.ValueMember = "MerchandiseId";
                ipeMerchandiseLookup.DisplayMember = "MerchandiseName";




            }
        }

        private void grvImportList_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            _dataChanged = true;
            var row = grvImportList.GetFocusedRow() as ImportDetailDTO;

            row.ExchangeRate = this.ExchangeRate;
        }

        //private List<WarehouseManagement.DataAccess.ImportDetail> _importDetails = new List<WarehouseManagement.DataAccess.ImportDetail>();

        private void grvImportList_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            var fr = grvImportList.GetFocusedRow() as ImportDetailDTO;

            _dataChanged = true;
            _dataSaved = false;
            btnCreateNewImportNumber.Enabled = true;
        }

        private void grvImportList_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {

        }

        private void ipeMerchandiseLookup_EditValueChanged(object sender, EventArgs e)
        {
            var edit = sender as GridLookUpEdit;
            //var view = edit.Properties.View as DevExpress.XtraGrid.Views.Grid.GridView;

            var fr = grvImportList.GetFocusedRow() as ImportDetailDTO;

            var selectedItem = (dynamic)edit.GetSelectedDataRow();
            fr.MerchandiseUnit = selectedItem.MerchandiseUnit;


        }



        public IEnumerable<CurrencyDTO> CurrencyList
        {
            get
            {
                return lkCurrency.Properties.DataSource as IEnumerable<CurrencyDTO>;
            }
            set
            {
                lkCurrency.Properties.DisplayMember = "CurrencyCode";
                lkCurrency.Properties.ValueMember = "CurrencyCode";
                lkCurrency.Properties.DataSource = value;
                lkCurrency.EditValue = "VND";
            }
        }

        private void lkCurrency_EditValueChanged(object sender, EventArgs e)
        {
            var edit = sender as LookUpEdit;
            if (_editMode == EditMode.New)
            {
                var abc = edit.GetColumnValue("ExchangeRateVND");
                if (abc != null)
                {
                    var exchangeRate = decimal.Parse(abc.ToString());

                    AssignExchangeRate(exchangeRate);
                }
            }
        }

        private void AssignExchangeRate(decimal value)
        {
            ExchangeRate = value;
            foreach (var item in ImportDetailList)
            {
                item.ExchangeRate = ExchangeRate;
            }
            grvImportList.RefreshData();
        }

        private void grvImportList_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {

            //var quantity = Convert.ToDecimal(grvImportList.GetRowCellValue(e.RowHandle, colQuantity));
            //if (quantity < 1)
            //{
            //    e.Valid = false;
            //    e.ErrorText = "Bạn hãy xem lại số lượng";
            //}
            var errorList = ValidateImportItem(e.RowHandle);
            if (errorList.Count() > 0)
            {
                e.Valid = false;
                e.ErrorText = string.Join("\n", errorList);
            }
        }

        private IEnumerable<string> ValidateImportItem(int rowHandle)
        {
            var colMerchandise = grvImportList.GetRowCellValue(rowHandle, this.colMerchandise);

            if (colMerchandise == null || Convert.ToInt32(colMerchandise) == 0)
            {
                yield return "Bạn chưa chọn mặt hàng";
            }

            var quantity = Convert.ToDecimal(grvImportList.GetRowCellValue(rowHandle, this.colQuantity));
            if (quantity < 1)
            {
                yield return "Bạn hãy xem lại số lượng nhập";
            }
        }

        private void grvImportList_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
        {
            if (grvImportList.FocusedColumn.FieldName == "Quantity")
            {
                if (Convert.ToDecimal(e.Value) < 1)
                {
                    e.ErrorText = "Bạn hãy xem lại số lượng nhập";
                    e.Valid = false;
                }
            }

        }




        public Guid SelectedImportItem
        {
            get
            {
                var handle = grvImportList.FocusedRowHandle;
                var row = grvImportList.GetRow(handle) as dynamic;
                if (row == null)
                    return Guid.Empty;
                return row.Id;
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (XtraMessageBox.Show("Bạn có chắc muốn xóa dòng này?", "Xóa", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == System.Windows.Forms.DialogResult.No)
                return;
            _presenter.DeleteSelectedItem();
            _dataChanged = true;
            _dataSaved = false;
        }

        private void ipeMerchandiseLookup_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)
            {
                NewEditMerchandise frm = new NewEditMerchandise();
                frm.OnMerchandiseSaved = new NewEditMerchandise.MerchandiseSavedHandler(OnMerchandiseAdded);
                frm.ShowDialog();
            }
        }

        private void OnMerchandiseAdded(bool success, bool isEdit)
        {
            _presenter.LoadMerchandiseLookupData();
        }

        private void grvImportList_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            HandleControls();
        }

        private void HandleControls()
        {

            btnDelete.Enabled = (this.SelectedImportItem != Guid.Empty);
            if (_editMode == EditMode.New)
            {
                btnSave.Enabled = this.ImportDetailList.Count > 0;

            }
            else
            {

            }
        }

        private void labelControl2_Click(object sender, EventArgs e)
        {

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            _presenter.OnImportSaved = new NewImportPresenter.ImportSaved(onImportSaved);
            _presenter.SaveImport();

        }

        private void onImportSaved(bool success)
        {
            if (success)
            {
                _dataSaved = true;
                CurrentEditMode = EditMode.EditExisting;
                //txtImportDate.Enabled = false;
                XtraMessageBox.Show("Nhập kho thành công. Tất cả thông tin đã được lưu.", "Nhập kho thành công", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                XtraMessageBox.Show("Đã xảy ra lỗi khi nhập kho. Thông tin mới nhập hiện vẫn chưa được lưu và không ảnh hưởng tới dữ liệu cũ, bạn hãy thử lại sau", "Lỗi khi nhập kho", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            if (this.OnImportSaved != null)
                OnImportSaved(success);
        }

        public void RefreshDataControls()
        {
            _presenter.LoadCurrencyLookupData();
            _presenter.LoadMerchandiseLookupData();
        }
        private void btnCreateNewImportNumber_Click(object sender, EventArgs e)
        {
            if (_dataChanged && !_dataSaved)
            {
                if (XtraMessageBox.Show("Dữ liệu chưa được lưu, bạn có chắc muốn tạo phiếu nhập mới?", "Tạo phiếu nhập mới", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No)
                    return;
            }
            _presenter.CreateNewImportNumber();
            _editMode = EditMode.New;

            //txtImportDate.Enabled = true;
            btnCreateNewImportNumber.Enabled = false;
        }


        public string ImportNumber
        {
            get
            {
                return txtImportNumber.Text;
            }
            set
            {
                txtImportNumber.Text = value;
            }
        }


        public NewEditImport.EditMode CurrentEditMode
        {
            get
            {
                return _editMode;
            }
            set
            {
                _editMode = value;
                if (_editMode == EditMode.New)
                {

                    //txtImportDate.Enabled = true;
                    lkSupplier.Enabled = true;
                    lkCurrency.Enabled = true;
                }
                else
                {
                    //txtImportDate.Enabled = false;
                    lkSupplier.Enabled = false;
                    lkCurrency.Enabled = false;
                }
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void NewEditImport_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_dataChanged && !_dataSaved)
            {
                var result = XtraMessageBox.Show("Dữ liệu chưa được lưu, bạn có muốn lưu trước khi đóng không?", "Lưu dữ liệu",
                   MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (result == DialogResult.Cancel)
                    e.Cancel = true;
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    btnSave_Click(sender, (EventArgs)e);
                }
            }
        }




        public int UsedCurrencyId
        {
            get
            {
                var item = lkCurrency.GetSelectedDataRow() as CurrencyDTO;
                return item.CurrencyId;
            }
            set
            {
                if (CurrencyList == null || CurrencyList.Count() == 0)
                {
                    _presenter.LoadCurrencyLookupData();
                }
                lkCurrency.EditValue = _currencyBC.GetCurrencyById(value).CurrencyCode;
            }
        }

        public decimal ExchangeRate
        {
            get
            {
                return txtExchangeRate.Value;
            }
            set
            {
                txtExchangeRate.Value = value;
            }
        }

        public void EnableCurrencySelection(bool enabled)
        {
            lkCurrency.Enabled = enabled;
        }
        public void EnableSupplierSelection(bool enabled)
        {
            lkSupplier.Enabled = enabled;
        }


        public int SupplierId
        {
            get
            {
                try
                {
                    return Convert.ToInt32(lkSupplier.EditValue);
                }
                catch { return -1; }
            }
            set
            {
                lkSupplier.EditValue = value;
            }
        }

        public string ImportForDocumentNumber
        {
            get
            {
                return txtForDocument.Text;
            }
            set { txtForDocument.Text = value; }
        }
        public IEnumerable<SupplierDTO> SupplierList
        {
            get
            {
                return lkSupplier.Properties.DataSource as IEnumerable<SupplierDTO>;
            }
            set
            {
                lkSupplier.Properties.DisplayMember = "SupplierName";
                lkSupplier.Properties.ValueMember = "Id";
                lkSupplier.Properties.DataSource = value;
                lkSupplier.Properties.PopupFormSize = new Size(lkSupplier.Size.Width, 200);

            }
        }

        private void lkSupplier_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)
            {
                NewEditSupplier frm = new NewEditSupplier(false);
                frm.OnOperationCompleted = new NewEditSupplier.OperationCompleted(NewEditSupplier_Completed);
                frm.ShowDialog();
            }
        }

        private void NewEditSupplier_Completed(bool success, bool isEditMode)
        {
            _presenter.LoadSupplierList();
        }

       
        private void lkCurrency_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Ellipsis)
            {
                _presenter.LoadCurrencyLookupData();
            }
        }
    }
}
